<template>
  <div class="common-layout">
    <el-container id="container">
      <el-main>
        <div id="condition">
          <el-input
              v-model="aNameFilter"
              style="width: 240px"
              placeholder="请输入演员姓名"
              size="large"
              clearable
          />
          <el-button type="primary" @click="handleAdd" size="large">新增演员</el-button>
          <el-button type="success" @click="handleQuery" size="large">查询</el-button>
        </div>
        <div id="tableDiv">
          <el-table
              id="table"
              :data="tableData"
              border
              show-overflow-tooltip
              size="large"
              table-layout="fixed"
              style="text-align: center">
            <el-table-column prop="aid" label="演员id"/>
            <el-table-column prop="aName" label="演员姓名"/>
            <el-table-column prop="aPic" label="演员图片">
              <template v-slot="{ row }">
                <el-image :src="imgPrefix + row.aPic" fit="cover" style="max-height: 100px;max-width: 100px"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <el-footer>
        <div id="pagination">
          <el-pagination
              style="float:right"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :current-page="currentPage"
              :disabled="false"
              :total="totalCount"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </el-footer>
    </el-container>
    <el-dialog
        v-model="addDialog"
        title="新增演员"
        width="500"
        align-center
    >
      <el-form
          ref="registerForm"
          label-position="right"
          label-width="auto"
          :model="actor"
          size="large"
          style="max-width: 600px">
        <el-form-item label="演员姓名:" label-position="right">
          <el-input v-model="actorAdd.aName" style="width: 240px"
                    placeholder="请输入演员姓名" clearable/>
        </el-form-item>
        <el-form-item style="height: 100px;">
          <!-- el-upload组件用于上传头像，隐藏相关默认显示内容 -->
          <!--这里ref不能用动态绑定,否则proxy.$refs.uploadRef获取不到-->
          <el-upload
              v-model:file-list="fileList"
              ref="uploadRef"
              :action="baseIp+':9090/upload/uploadFile'"
              :show-file-list="false"
              :auto-upload="false"
              accept=".jpg,.jpeg,.png,.bmp"
              :on-change="handleFileChange"
              :on-success="handleSuccess"
              :on-error="handleError"
              style="margin:0 auto;"
          ><!--:on-exceed="handleExceed"-->
            <!--:limit="1"-->
            <el-tooltip
                class="box-item"
                effect="light"
                content="点击添加演员图片"
                placement="top-start"
            >
              <el-avatar :size="100" :src="aPicUrlDefault"/>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="doAdd">新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ElNotification, ElMessageBox, ElUpload} from "element-plus";
import {ref, reactive, onMounted, inject, getCurrentInstance} from "vue";
import axios from "axios";
import sessionStorage from "@/SessionStorage.js";
import {request2} from "@/request.js";

const {proxy} = getCurrentInstance();

const imgPrefix = inject('imgPrefix');
const aNameFilter = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const totalCount = ref(0);
const tableData = reactive([]);

const actorQueryDto = reactive({
  aName: aNameFilter.value,
  pageNo: currentPage.value,
  pageSize: pageSize.value,
});

const baseIp = import.meta.env.VITE_APP_API_URL;

const handleQuery = () => {
  actorQueryDto.aName = aNameFilter.value;
  actorQueryDto.pageNo = currentPage.value;
  actorQueryDto.pageSize = pageSize.value;
  request2({
    url: "/actor/list",
    method: "post",
    data: actorQueryDto
  }).then(res => {
    if ('200' === res.code && res.data !== null) {
      tableData.splice(0, tableData.length);
      tableData.push(...res.data.page.list);
      pageSize.value = res.data.page.pageSize;
      currentPage.value = res.data.page.pageNo;
      totalCount.value = res.data.page.totalCount;
    }
  });
};

const handleAdd = () => {
  // 新增操作
  addDialog.value = true;

  doAdd();
};

const handleEdit = (row) => {

  ElMessageBox.prompt('修改演员信息', '提示', {
    inputValue: row.aName,
    inputPlaceholder: '请输入演员姓名',
  }).then(({value}) => {
    const actor = reactive({
      aid: row.aid,
      aName: value
    })
    // 提交修改
    request2({
      url: '/actor/updateActor',
      method: "post",
      data: actor,
    }).then(res => {
      if (res.code === '200') {
        ElNotification.success("修改成功！");
        handleQuery();
      } else {
        ElNotification.error(res.msg);
      }
    });
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该演员, 是否继续?', '提示', {
    type: 'warning'
  }).then(() => {
    request2(`/actor/deleteActor?aid=` + row.aid).then(res => {
      if ('200' === res.data.code) {
        handleQuery();
        ElNotification({
          type: 'success',
          message: '删除成功!'
        });
      } else {
        ElNotification.error(res.data.msg);
      }
    });
  });
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  actorQueryDto.pageNo = newPage;
  handleQuery();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  actorQueryDto.pageSize = newSize;
  handleQuery();
};

onMounted(() => {
  handleQuery();
});


const addDialog = ref(false);
const actorAdd = reactive({
  aName: null,
  aPic: null
})

// 图片上传
// 演员图片上传历史
let fileList = reactive([])

const fileTypes = ref(["image/bmp", "image/jpeg", "image/png"]);
const beforeUpload = (file) => {
  const fileType = ref();
  fileType.value = file.raw == null ? file.type : file.raw.type;
  if (!fileTypes.value.includes(fileType.value)) {
    ElNotification.error("只能上传bmp/jpeg/jpg/png图片");
    return false;
  }
  if (file.size / 1024 / 1024 > 2) {
    ElNotification.error("上传图片最大不超过2MB!");
    return false;
  }
  return true;
}
const handleFileChange = (uploadFile, uploadFiles) => {
  if (!beforeUpload(uploadFile.raw)) {
    return;
  }
  // 展示
  const reader = new FileReader();
  reader.onloadend = () => {
    const base64Data = reader.result;
    if (base64Data) {
      // 将Base64数据存储到sessionStorage，键名为'tempAvatar'，方便后续提交时使用
      sessionStorage.setItem('tempAvatar', base64Data);
      aPicUrlDefault.value = base64Data;
    }
  };
  if (uploadFile.raw) {
    console.log("正在读取选择的文件，请稍候...");
    reader.readAsDataURL(uploadFile.raw);
  } else {
    ElNotification.error("没有获取到有效的文件原始数据，无法进行读取操作");
  }

  uploadFiles.forEach(item => {
    console.log("uploadFiles的内容：" + JSON.stringify(item));
  })

  if (uploadFiles.length > 1) {
    const uploadRefObj = proxy.$refs.uploadRef;
    // 1. 清空list
    uploadRefObj.clearFiles();
    // 2. 上传最新的
    uploadRefObj.handleStart(uploadFile.raw);
  }


};
// 文件上传成功后的回调函数
const handleSuccess = (res, file, fileList) => {
  console.log('文件上传成功', res, file, fileList);
  if ('200' === res.code) {
    console.log("后端接口返回正常！");
    const ossUPic = res.data;
    reqAdd(ossUPic);
  }
};
// 文件上传失败后的回调函数
const handleError = (response, file, fileList) => {
  console.log('文件上传失败', response, file, fileList);
  ElNotification.error("图片上传失败！");
};
const aPicUrlDefault = ref(imgPrefix + "defaultHeaderCircle.png");

const doAdd = () => {
  // 头像没变化，ossUPic使用旧的即可，然后直接修改用户信息
  if (aPicUrlDefault.value === imgPrefix + "defaultHeaderCircle.png") {
    reqAdd();
  } else {
    // 头像有变化，则先调用后端接口上传oss，利用文件成功上传的回调函数拿到返回给前端的图片名，然后携带输入框信息一起更新
    // 保留最新的最后一个，然后上传
    const uploadRefObj = proxy.$refs.uploadRef;
    uploadRefObj.submit();
  }


}

const reqAdd = (aPic) => {
  const actor = reactive({
    aName: actorAdd.aName,
    aPic: "defaultHeaderCircle.png"
  })
  // 此时这里的uPic需要去掉imgPrefix，只保留文件名
  if (aPicUrlDefault.value !== imgPrefix + "defaultHeaderCircle.png") {
    actor.aPic = aPic;
  }

  request2({
    url: "/actor/addActor",
    method: "post",
    data: actor
  }).then(res => {
    if ('200' === res.data.code && res.data.data !== null) {
      ElNotification.success("添加成功！");
      actor.aPic = imgPrefix + "defaultHeaderCircle.png";
      actor.aName = null;
      addDialog.value = false;
      handleQuery();
    }
  });
}
</script>

<style scoped>
.common-layout {
  width: 100%;
  height: 100%;
}

#condition {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px 0;
}

#tableDiv {
  text-align: center;
}

#pagination {
  float: right;
}
</style>
